import React, { useState, useEffect, useRef } from 'react';
import OriginChart from './OriginChart.jsx';
import ChartStyleModal from './ChartStyleModal/index.jsx';
import FileUploader from './FileUploader/index.jsx';
import { convertJsonToEchartsFormat, validateData } from '../utils/dataConverter.js';

// 模拟数据的JSON格式
const mockDataJson = {
  "title": {
    "text": "标题测试数据"
  },
  "series": [
    {
      "name": "系列1",
      "type": "line",
      "data": [
        { "x": "1月", "y": 55 },
        { "x": "2月", "y": 66 },
        { "x": "3月", "y": 68 },
        { "x": "4月", "y": 60 },
        { "x": "5月", "y": 69 },
        { "x": "6月", "y": 77 },
        { "x": "7月", "y": 70 },
        { "x": "8月", "y": 79 },
        { "x": "9月", "y": 81 }
      ]
    },
    {
      "name": "系列2",
      "type": "line",
      "data": [
        { "x": "1月", "y": 45 },
        { "x": "2月", "y": 56 },
        { "x": "3月", "y": 58 },
        { "x": "4月", "y": 50 },
        { "x": "5月", "y": 59 },
        { "x": "6月", "y": 67 },
        { "x": "7月", "y": 60 },
        { "x": "8月", "y": 69 },
        { "x": "9月", "y": 71 }
      ]
    },
    {
      "name": "系列3",
      "type": "bar",
      "data": [
        { "x": "1月", "y": 35 },
        { "x": "2月", "y": 46 },
        { "x": "3月", "y": 48 },
        { "x": "4月", "y": 40 },
        { "x": "5月", "y": 49 },
        { "x": "6月", "y": 57 },
        { "x": "7月", "y": 50 },
        { "x": "8月", "y": 59 },
        { "x": "9月", "y": 61 }
      ]
    }
  ]
}




// 生成模拟数据的函数
const generateMockData = () => {
  const convertedData = convertJsonToEchartsFormat(mockDataJson);

  // 验证转换后的数据
  if (!validateData(convertedData)) {
    console.error('数据转换后验证失败');
  } else {
    console.log('数据转换和验证成功:', convertedData);
  }

  return convertedData;
};

const ScatterLineChart = ({ initialData = generateMockData() }) => {
  // 使用状态管理数据，以便能够动态添加
  const [data, setData] = useState(initialData);
  const [modalVisible, setModalVisible] = useState(false);
  const [uploaderVisible, setUploaderVisible] = useState(false);
  const [error, setError] = useState(null);
  const [uploadStatus, setUploadStatus] = useState('');

  // 用于保存图表实例的引用
  const chartInstanceRef = useRef(null);

  // 计算初始数据范围
  const getInitialDataRanges = (data) => {
    let xMin = Infinity;
    let xMax = -Infinity;
    let yMin = Infinity;
    let yMax = -Infinity;
    let hasStringX = false;

    // 处理数据点的函数
    const processDataPoints = (lineData) => {
      if (lineData && Array.isArray(lineData)) {
        lineData.forEach(point => {
          const [x, y] = point.value;

          if (typeof x === 'string') {
            hasStringX = true;
          } else if (typeof x === 'number' && isFinite(x)) {
            xMin = Math.min(xMin, x);
            xMax = Math.max(xMax, x);
          }

          if (typeof y === 'number' && isFinite(y)) {
            yMin = Math.min(yMin, y);
            yMax = Math.max(yMax, y);
          }
        });
      }
    };

    // 处理多系列数据
    if (data && data.multiSeries && data.allSeries) {
      data.allSeries.forEach(series => {
        processDataPoints(series.line);
      });
    } else if (data && data.line && Array.isArray(data.line)) {
      // 处理单条线的数据（向后兼容）
      processDataPoints(data.line);
    }

    // 计算合理的Y轴刻度间隔
    const calculateYMajorScaleValue = (min, max) => {
      if (!isFinite(min) || !isFinite(max)) return 1;

      const range = max - min;
      if (range <= 0) return 1;

      // 目标是有6-8个主刻度
      const targetSteps = 6;
      const rawStep = range / targetSteps;

      // 找到合适的刻度间隔（1, 2, 5, 10, 20, 50, 100等）
      const magnitude = Math.pow(10, Math.floor(Math.log10(rawStep)));
      const normalizedStep = rawStep / magnitude;

      let step;
      if (normalizedStep <= 1) {
        step = 1 * magnitude;
      } else if (normalizedStep <= 2) {
        step = 2 * magnitude;
      } else if (normalizedStep <= 5) {
        step = 5 * magnitude;
      } else {
        step = 10 * magnitude;
      }

      return Math.max(step, 1);
    };

    // 计算合适的Y轴范围
    let yScaleStart, yScaleEnd, yMajorScaleValue;

    if (!isFinite(yMin) || !isFinite(yMax)) {
      yScaleStart = -2;
      yScaleEnd = 2;
      yMajorScaleValue = 1;
    } else {
      yMajorScaleValue = calculateYMajorScaleValue(yMin, yMax);

      // 根据刻度间隔调整边距，确保范围是刻度间隔的整数倍
      const yMinRounded = Math.floor(yMin / yMajorScaleValue) * yMajorScaleValue;
      const yMaxRounded = Math.ceil(yMax / yMajorScaleValue) * yMajorScaleValue;

      // 如果数据点太接近边界，再扩展一个刻度间隔
      yScaleStart = (yMin - yMinRounded) < yMajorScaleValue * 0.1 ? yMinRounded - yMajorScaleValue : yMinRounded;
      yScaleEnd = (yMaxRounded - yMax) < yMajorScaleValue * 0.1 ? yMaxRounded + yMajorScaleValue : yMaxRounded;

      yScaleStart = Math.round(yScaleStart * 10) / 10;
      yScaleEnd = Math.round(yScaleEnd * 10) / 10;
    }

    // 设置默认范围
    return {
      xScaleStart: hasStringX || !isFinite(xMin) ? 0 : Math.floor((xMin - Math.max((xMax - xMin) * 0.1, 0.5)) * 10) / 10,
      xScaleEnd: hasStringX || !isFinite(xMax) ? 10 : Math.ceil((xMax + Math.max((xMax - xMin) * 0.1, 0.5)) * 10) / 10,
      yScaleStart: yScaleStart,
      yScaleEnd: yScaleEnd,
      xMajorScaleValue: hasStringX || !isFinite(xMin) ? 1 : Math.max(1, Math.ceil((xMax - xMin) / 8)),
      yMajorScaleValue: yMajorScaleValue
    };
  };

  const initialRanges = getInitialDataRanges(initialData);

  const [chartStyle, setChartStyle] = useState({
    // 显示相关
    showTopAxis: false,
    showBottomAxis: true,
    showLeftAxis: true,
    showRightAxis: false,

    // 图表类型
    chartType: 'line',

    // 系列颜色配置（为多条数据预留）
    seriesColors: [
      '#5470c6', // 系列1
      '#91cc75', // 系列2  
      '#fac858', // 系列3
      '#ee6666', // 系列4
      '#73c0de', // 系列5
      '#3ba272', // 系列6
      '#fc8452', // 系列7
      '#9a60b4', // 系列8
      '#ea7ccc'  // 系列9
    ],

    // 标题相关
    titleShow: true,
    titleText: "", // 留空，使用数据中的name
    titleFontSize: 16,
    titleColor: "#333333",
    titlePosition: "center",
    titleTop: "5%", // 增加标题与图表的间距
    titleLeft: "center",
    titleFontFamily: "Microsoft YaHei",
    titleFontWeight: "normal",
    titleFontStyle: "normal",

    // 刻度相关
    xScaleStart: initialRanges.xScaleStart,
    xScaleEnd: initialRanges.xScaleEnd,
    xScaleType: 'value',
    xScaleAdjustment: 'normal',
    marginAdjustment: 8,
    xIsFlipped: false,

    // Y轴刻度
    yScaleStart: initialRanges.yScaleStart,
    yScaleEnd: initialRanges.yScaleEnd,
    yScaleType: 'value',
    yScaleAdjustment: 'normal',
    yIsFlipped: false,

    // 主刻度配置
    xMajorScaleType: 'byInterval',
    xMajorScaleValue: initialRanges.xMajorScaleValue,
    xMajorScaleAnchor: '',

    // Y轴主刻度配置
    yMajorScaleType: 'byInterval',
    yMajorScaleValue: initialRanges.yMajorScaleValue,
    yMajorScaleAnchor: '',

    // 次刻度配置
    xMinorScaleType: 'byCount',
    xMinorScaleCount: 1,

    // Y轴次刻度配置
    yMinorScaleType: 'byCount',
    yMinorScaleCount: 1,

    // 刻度线标签相关
    axisLabelShow: true,
    axisLabelColor: '#666666',
    axisLabelFontSize: 12,

    // 网格相关
    gridShow: true,
    gridColor: '#e0e0e0',
    gridType: 'solid',

    // 轴线和刻度线相关 - 底部轴
    bottomAxisLineShow: true,
    bottomAxisLineColor: '#333333',
    bottomAxisLineWidth: 1.5,
    bottomAxisLineArrow: false,
    bottomMajorTickShow: true,
    bottomMajorTickLength: 8,
    bottomMajorTickColor: '#000000',
    bottomMajorTickWidth: 1,
    bottomMajorTickType: 'outside',
    bottomMinorTickShow: true,
    bottomMinorTickLength: 4,
    bottomMinorTickColor: '#000000',
    bottomMinorTickWidth: 1,
    bottomMinorTickType: 'outside',

    // 轴线和刻度线相关 - 顶部轴
    topAxisLineShow: true,
    topAxisLineColor: '#333333',
    topAxisLineWidth: 1.5,
    topAxisLineArrow: false,
    topMajorTickShow: true,
    topMajorTickLength: 8,
    topMajorTickColor: '#000000',
    topMajorTickWidth: 1,
    topMajorTickType: 'outside',
    topMinorTickShow: true,
    topMinorTickLength: 4,
    topMinorTickColor: '#000000',
    topMinorTickWidth: 1,
    topMinorTickType: 'outside',

    // 轴线和刻度线相关 - 左侧轴
    leftAxisLineShow: true,
    leftAxisLineColor: '#333333',
    leftAxisLineWidth: 1.5,
    leftAxisLineArrow: false,
    leftMajorTickShow: true,
    leftMajorTickLength: 8,
    leftMajorTickColor: '#000000',
    leftMajorTickWidth: 1,
    leftMajorTickType: 'outside',
    leftMinorTickShow: true,
    leftMinorTickLength: 4,
    leftMinorTickColor: '#000000',
    leftMinorTickWidth: 1,
    leftMinorTickType: 'outside',

    // 轴线和刻度线相关 - 右侧轴
    rightAxisLineShow: true,
    rightAxisLineColor: '#333333',
    rightAxisLineWidth: 1.5,
    rightAxisLineArrow: false,
    rightMajorTickShow: true,
    rightMajorTickLength: 8,
    rightMajorTickColor: '#000000',
    rightMajorTickWidth: 1,
    rightMajorTickType: 'outside',
    rightMinorTickShow: true,
    rightMinorTickLength: 4,
    rightMinorTickColor: '#000000',
    rightMinorTickWidth: 1,
    rightMinorTickType: 'outside',

    // 网格相关配置 - X轴
    xGridMainShow: true,
    xGridMainColor: '#cccccc',
    xGridMainType: 'solid',
    xGridMainWidth: 0.5,
    xGridMinorShow: false,
    xGridMinorColor: '#e0e0e0',
    xGridMinorType: 'dashed',
    xGridMinorWidth: 0.3,

    // 网格相关配置 - Y轴
    yGridMainShow: true,
    yGridMainColor: '#cccccc',
    yGridMainType: 'solid',
    yGridMainWidth: 0.5,
    yGridMinorShow: false,
    yGridMinorColor: '#e0e0e0',
    yGridMinorType: 'dashed',
    yGridMinorWidth: 0.3,

    // 特殊刻度线相关
    splitLineShow: true,
    splitLineColor: '#e0e0e0',
    splitLineType: 'solid',

    // 断点相关
    breakPointShow: false,
    breakPointSymbol: 'circle',
    breakPointColor: '#000000',

    // 轴须相关
    axisPaddingShow: true,
    axisPaddingSyncAxes: false,
    axisPaddingColor: "#000000",
    axisPaddingWidth: 0.5,
    axisPaddingOpacity: 0,
    axisPaddingSize: 8,
    axisPaddingOverlap: false,
    axisPaddingSpacing: 10,
    axisPaddingMargin: 5,
    axisPaddingShowBoundary: true,
    axisPaddingShowParallel: true,

    // 各轴的轴须显示控制
    topAxisPaddingShow: true,
    bottomAxisPaddingShow: true,
    leftAxisPaddingShow: true,
    rightAxisPaddingShow: true,

    // 参照线相关
    hReferenceLineShow: false,
    hReferenceLineColor: '#ff0000',
    hReferenceLineValue: 0,
    hReferenceLineWidth: 1,
    hReferenceLineType: 'solid',

    vReferenceLineShow: false,
    vReferenceLineColor: '#0000ff',
    vReferenceLineValue: 0,
    vReferenceLineWidth: 1,
    vReferenceLineType: 'solid',

    // 刻度线标签相关 - 底部轴
    bottomAxisLabelShow: true,
    bottomAxisLabelColor: '#666666',
    bottomAxisLabelFontSize: 12,
    bottomAxisLabelFontFamily: 'Microsoft YaHei',
    bottomAxisLabelRotate: 0,
    bottomAxisLabelDistance: 8,

    // 刻度线标签相关 - 顶部轴
    topAxisLabelShow: true,
    topAxisLabelColor: '#666666',
    topAxisLabelFontSize: 12,
    topAxisLabelFontFamily: 'Microsoft YaHei',
    topAxisLabelRotate: 0,
    topAxisLabelDistance: 8,

    // 刻度线标签相关 - 左侧轴
    leftAxisLabelShow: true,
    leftAxisLabelColor: '#666666',
    leftAxisLabelFontSize: 12,
    leftAxisLabelFontFamily: 'Microsoft YaHei',
    leftAxisLabelRotate: 0,
    leftAxisLabelDistance: 8,

    // 刻度线标签相关 - 右侧轴
    rightAxisLabelShow: true,
    rightAxisLabelColor: '#666666',
    rightAxisLabelFontSize: 12,
    rightAxisLabelFontFamily: 'Microsoft YaHei',
    rightAxisLabelRotate: 0,
    rightAxisLabelDistance: 8,
  });

  // 计算数据的范围
  // 在ScatterLineChart.jsx中添加以下修改

// 修改calculateDataRanges函数，添加对实时数据的支持
  const calculateDataRanges = (data) => {
    let xMin = Infinity;
    let xMax = -Infinity;
    let yMin = Infinity;
    let yMax = -Infinity;
    let hasStringX = false;

    const processDataPoints = (lineData) => {
      if (lineData && Array.isArray(lineData)) {
        lineData.forEach(point => {
          const [x, y] = point.value;
          
          if (typeof x === 'string') {
            hasStringX = true;
          } else if (typeof x === 'number' && isFinite(x)) {
            xMin = Math.min(xMin, x);
            xMax = Math.max(xMax, x);
          }
          
          if (typeof y === 'number' && isFinite(y)) {
            yMin = Math.min(yMin, y);
            yMax = Math.max(yMax, y);
          }
        });
      }
    };

    // 处理多系列实时数据
    if (data?.multiSeries && data?.allSeries) {
      data.allSeries.forEach(series => {
        processDataPoints(series.line);
      });
    } else if (data?.line) {
      processDataPoints(data.line);
    }

    // 如果没有有效的x数据（可能是首次渲染），设置默认范围
    if (!isFinite(xMin) || !isFinite(xMax)) {
      xMin = 0;
      xMax = 10;
    }

    // 如果没有有效的y数据（可能是首次渲染），设置默认范围
    if (!isFinite(yMin) || !isFinite(yMax)) {
      yMin = -2;
      yMax = 2;
    }

    // 计算合理的Y轴刻度间隔
    const calculateYMajorScaleValue = (min, max) => {
      const range = max - min;
      if (range <= 0) return 1;
      
      const targetSteps = 6;
      const rawStep = range / targetSteps;
      const magnitude = Math.pow(10, Math.floor(Math.log10(rawStep)));
      const normalizedStep = rawStep / magnitude;
      
      let step;
      if (normalizedStep <= 1) step = 1 * magnitude;
      else if (normalizedStep <= 2) step = 2 * magnitude;
      else if (normalizedStep <= 5) step = 5 * magnitude;
      else step = 10 * magnitude;
      
      return Math.max(step, 1);
    };

    const yMajorScaleValue = calculateYMajorScaleValue(yMin, yMax);
    
    return {
      xMin,
      xMax,
      yMin,
      yMax,
      yMajorScaleValue,
      xType: hasStringX ? 'category' : 'value'
    };
  };

  // 在组件中添加对实时数据的支持
  const ScatterLineChart = ({ initialData, chartStyle: initialChartStyle }) => {
    const [data, setData] = useState(initialData);
    const [chartStyle, setChartStyle] = useState({
      ...defaultChartStyle,
      ...initialChartStyle
    });
    
    // 其他现有代码...
    
    // 修改handleDataLoaded函数以支持实时数据
    const handleDataLoaded = (newData, originalData) => {
      try {
        setData(newData);
        setError(null);
        
        const newDataRanges = calculateDataRanges(newData);
        
        setChartStyle(prevStyle => ({
          ...prevStyle,
          xScaleStart: newDataRanges.xMin,
          xScaleEnd: newDataRanges.xMax,
          yScaleStart: newDataRanges.yMin,
          yScaleEnd: newDataRanges.yMax,
          yMajorScaleValue: newDataRanges.yMajorScaleValue,
          ...((!prevStyle.titleText || prevStyle.titleText.trim() === '') && newData.title ? {
            titleText: newData.title
          } : {})
        }));
      } catch (error) {
        console.error('数据设置失败:', error);
        setError('数据设置失败');
      }
    };
    
    // 其他现有代码...
  };

  const dataRanges = calculateDataRanges(data);

  // 检测数据类型，确定轴类型
  const detectAxisTypes = (data) => {
    if (!data || !data.line || data.line.length === 0) {
      return { xAxisType: 'value', yAxisType: 'value' };
    }

    const firstPoint = data.line[0];
    const xType = typeof firstPoint.value[0] === 'string' ? 'category' : 'value';

    return {
      xAxisType: xType,
      yAxisType: 'value' // y轴始终为数值轴
    };
  };

  const axisTypes = detectAxisTypes(data);

  // 计算实际的刻度间隔
  const calculateInterval = (start, end, majorValue, type) => {
    try {
      if (type === 'byInterval') {
        return majorValue;
      } else {
        // 如果是按数量，则计算间隔
        const interval = Math.abs(end - start) / (majorValue - 1);
        return isFinite(interval) ? interval : 1; // 防止除以零或无限值
      }
    } catch (error) {
      console.error('计算刻度间隔时出错:', error);
      return 1; // 返回默认值
    }
  };

  // 计算优化后的刻度范围
  const calculateNiceRange = (start, end) => {
    try {
      if (!isFinite(start) || !isFinite(end)) {
        return { start: 0, end: 10 }; // 默认范围
      }
      const range = end - start;
      if (range === 0) {
        return { start: start - 1, end: end + 1 }; // 处理起始值等于结束值的情况
      }
      const magnitude = Math.pow(10, Math.floor(Math.log10(Math.abs(range))));
      const niceStart = Math.floor(start / magnitude) * magnitude;
      const niceEnd = Math.ceil(end / magnitude) * magnitude;
      return { start: niceStart, end: niceEnd };
    } catch (error) {
      console.error('计算优化刻度范围时出错:', error);
      return { start: 0, end: 10 }; // 返回默认值
    }
  };

  const getGridLineConfig = (axis, style) => ({
    splitLine: {
      show: style[`${axis}GridMainShow`] ?? true,
      lineStyle: {
        color: style[`${axis}GridMainColor`] || '#cccccc',
        type: style[`${axis}GridMainType`] || 'solid',
        width: style[`${axis}GridMainWidth`] || 0.5,
      },
    },
    minorSplitLine: {
      show: style[`${axis}GridMinorShow`] ?? false,
      lineStyle: {
        color: style[`${axis}GridMinorColor`] || '#e0e0e0',
        type: style[`${axis}GridMinorType`] || 'dashed',
        width: style[`${axis}GridMinorWidth`] || 0.3,
      },
    },
  });

  const getMarkLineConfig = (axis, style) => {
    if (!style[`${axis}GridExtraEnable`]) return undefined;
    const value = style[`${axis}GridExtraValue`] || 0;
    const isOpposite = style[`${axis}GridExtraOpposite`];
    return {
      symbol: 'none',
      label: { show: true, formatter: `{b}: {c}` },
      lineStyle: {
        color: '#faad14',
        type: 'dashed',
        width: 1.5,
      },
      data: [
        axis === 'x'
          ? { xAxis: value, name: isOpposite ? '对面' : 'X' }
          : { yAxis: value, name: isOpposite ? '对面' : 'Y' },
      ],
    };
  };

  const xGrid = getGridLineConfig('x', chartStyle);
  const yGrid = getGridLineConfig('y', chartStyle);
  const xMarkLine = getMarkLineConfig('x', chartStyle);
  const yMarkLine = getMarkLineConfig('y', chartStyle);

  // 获取单个轴的配置
  const getAxisConfig = (axisKey, style, axisType) => ({
    show: style[`${axisKey}AxisLineShow`] ?? true,
    position: axisKey, // ECharts会自动识别top/bottom/left/right
    axisLine: {
      show: style[`${axisKey}AxisLineShow`] ?? true,
      lineStyle: {
        color: style[`${axisKey}AxisLineColor`] || '#000',
        width: style[`${axisKey}AxisLineWidth`] || 1.5,
      },
      symbol: style[`${axisKey}AxisLineArrow`] ? ['none', 'arrow'] : undefined,
      symbolSize: style[`${axisKey}AxisLineArrow`] ? [8, 16] : undefined,
    },
    axisTick: {
      show: style[`${axisKey}MajorTickShow`] ?? true,
      alignWithLabel: false,
      length: style[`${axisKey}MajorTickLength`] || 8,
      lineStyle: {
        color: style[`${axisKey}MajorTickColor`] || '#000',
        width: style[`${axisKey}MajorTickWidth`] || 1,
      },
      inside: style[`${axisKey}MajorTickType`] === 'inside',
    },
    minorTick: {
      show: style[`${axisKey}MinorTickShow`] ?? true,
      length: style[`${axisKey}MinorTickLength`] || 4,
      lineStyle: {
        color: style[`${axisKey}MinorTickColor`] || '#000',
        width: style[`${axisKey}MinorTickWidth`] || 1,
      },
      inside: style[`${axisKey}MinorTickType`] === 'inside',
    },
    axisLabel: {
      show: style[`${axisKey}AxisLabelShow`] ?? true,
      color: style[`${axisKey}AxisLabelColor`] || '#666666',
      fontSize: style[`${axisKey}AxisLabelFontSize`] || 12,
      fontFamily: style[`${axisKey}AxisLabelFontFamily`] || 'Microsoft YaHei',
      rotate: style[`${axisKey}AxisLabelRotate`] || 0,
      margin: style[`${axisKey}AxisLabelDistance`] || 8
    },
    splitLine: {
      show: style[`${axisKey}GridMainShow`] ?? true,
      lineStyle: {
        color: style[`${axisKey}GridMainColor`] || '#cccccc',
        type: style[`${axisKey}GridMainType`] || 'solid',
        width: style[`${axisKey}GridMainWidth`] || 0.5,
      },
    },
    minorSplitLine: {
      show: style[`${axisKey}GridMinorShow`] ?? false,
      lineStyle: {
        color: style[`${axisKey}GridMinorColor`] || '#e0e0e0',
        type: style[`${axisKey}GridMinorType`] || 'dashed',
        width: style[`${axisKey}GridMinorWidth`] || 0.3,
      },
    },
  });

  const xAxisConfigBottom = getAxisConfig('bottom', chartStyle, 'x');
  const xAxisConfigTop = getAxisConfig('top', chartStyle, 'x');
  const yAxisConfigLeft = getAxisConfig('left', chartStyle, 'y');
  const yAxisConfigRight = getAxisConfig('right', chartStyle, 'y');

  // 标度类型映射函数
  const getEchartsAxisTypeAndParams = (scaleType) => {
    switch (scaleType) {
      case 'value':
        return { type: 'value' };
      case 'log10':
        return { type: 'log', logBase: 10 };
      case 'ln':
        return { type: 'log', logBase: Math.E };
      case 'log2':
        return { type: 'log', logBase: 2 };
      case 'category':
        return { type: 'category' };
      case 'date':
      case 'time':
      case 'datetime':
        return { type: 'time' };
      // 下面这些暂时 fallback 到 value，后续可自定义刻度
      case 'probability':
      case 'probit':
      case 'logit':
      case 'gompertz':
      case 'weibull':
      case 'reciprocal':
      case 'percent':
        return { type: 'value' };
      default:
        return { type: 'value' };
    }
  };

  // 计算轴须的位置和样式
  const calculateRugMarks = () => {
    if (!chartStyle.axisPaddingShow || !data || !data.line || !Array.isArray(data.line)) return [];

    const graphics = [];

    // 左轴轴须
    if (chartStyle.showLeftAxis && chartStyle.leftAxisPaddingShow) {
      graphics.push({
        type: 'group',
        left: 0,
        top: `${chartStyle.axisPaddingMargin}%`,
        bottom: `${chartStyle.axisPaddingMargin}%`,
        width: `${chartStyle.axisPaddingSize}%`,
        silent: true,
        children: data.line.map(point => ({
          type: 'line',
          shape: {
            x1: chartStyle.axisPaddingShowBoundary ? 0 : '20%',
            y1: point.value[1],
            x2: chartStyle.axisPaddingShowParallel ? '100%' : '80%',
            y2: point.value[1]
          },
          style: {
            stroke: chartStyle.axisPaddingColor,
            lineWidth: chartStyle.axisPaddingWidth,
            opacity: (100 - chartStyle.axisPaddingOpacity) / 100
          }
        }))
      });
    }

    // 右轴轴须
    if (chartStyle.showRightAxis && chartStyle.rightAxisPaddingShow &&
      (!chartStyle.axisPaddingSyncAxes || !chartStyle.showLeftAxis || !chartStyle.leftAxisPaddingShow)) {
      graphics.push({
        type: 'group',
        right: 0,
        top: `${chartStyle.axisPaddingMargin}%`,
        bottom: `${chartStyle.axisPaddingMargin}%`,
        width: `${chartStyle.axisPaddingSize}%`,
        silent: true,
        children: data.line.map(point => ({
          type: 'line',
          shape: {
            x1: chartStyle.axisPaddingShowBoundary ? 0 : '20%',
            y1: point.value[1],
            x2: chartStyle.axisPaddingShowParallel ? '100%' : '80%',
            y2: point.value[1]
          },
          style: {
            stroke: chartStyle.axisPaddingColor,
            lineWidth: chartStyle.axisPaddingWidth,
            opacity: (100 - chartStyle.axisPaddingOpacity) / 100
          }
        }))
      });
    }

    // 下轴轴须
    if (chartStyle.showBottomAxis && chartStyle.bottomAxisPaddingShow) {
      graphics.push({
        type: 'group',
        left: '10%',
        right: '5%',
        bottom: 0,
        height: `${chartStyle.axisPaddingSize}%`,
        silent: true,
        children: data.line.map(point => ({
          type: 'line',
          shape: {
            x1: point.value[0],
            y1: chartStyle.axisPaddingShowBoundary ? 0 : '20%',
            x2: point.value[0],
            y2: chartStyle.axisPaddingShowParallel ? '100%' : '80%'
          },
          style: {
            stroke: chartStyle.axisPaddingColor,
            lineWidth: chartStyle.axisPaddingWidth,
            opacity: (100 - chartStyle.axisPaddingOpacity) / 100
          }
        }))
      });
    }

    // 上轴轴须
    if (chartStyle.showTopAxis && chartStyle.topAxisPaddingShow &&
      (!chartStyle.axisPaddingSyncAxes || !chartStyle.showBottomAxis || !chartStyle.bottomAxisPaddingShow)) {
      graphics.push({
        type: 'group',
        left: '10%',
        right: '5%',
        top: 0,
        height: `${chartStyle.axisPaddingSize}%`,
        silent: true,
        children: data.line.map(point => ({
          type: 'line',
          shape: {
            x1: point.value[0],
            y1: chartStyle.axisPaddingShowBoundary ? 0 : '20%',
            x2: point.value[0],
            y2: chartStyle.axisPaddingShowParallel ? '100%' : '80%'
          },
          style: {
            stroke: chartStyle.axisPaddingColor,
            lineWidth: chartStyle.axisPaddingWidth,
            opacity: (100 - chartStyle.axisPaddingOpacity) / 100
          }
        }))
      });
    }

    return graphics;
  };

  // 获取基础图表配置
  const getBaseOptions = () => {
    // 优先使用用户设置的标题，如果用户没有设置则使用数据中的标题，最后使用系列名称
    let titleText;
    if (chartStyle.titleText && chartStyle.titleText.trim() !== '') {
      // 用户在设置中输入了标题
      titleText = chartStyle.titleText;
    } else if (data?.title && data.title.trim() !== '') {
      // 数据中有标题
      titleText = data.title;
    } else if (data?.seriesInfo?.name) {
      // 使用第一个系列的名称
      titleText = data.seriesInfo.name;
    } else {
      // 默认标题
      titleText = chartStyle.chartType === 'pie' ? '饼图' : '图表';
    }

    return {
      backgroundColor: '#fff',
      title: {
        show: chartStyle.titleShow === undefined ? true : chartStyle.titleShow,
        text: titleText,
        left: chartStyle.titleLeft || "center",
        top: chartStyle.titleTop || "5%",
        textStyle: {
          fontSize: chartStyle.titleFontSize || 16,
          color: chartStyle.titleColor || "#333333",
          fontFamily: chartStyle.titleFontFamily || "Microsoft YaHei",
          fontWeight: chartStyle.titleFontWeight || "normal",
          fontStyle: chartStyle.titleFontStyle || "normal"
        }
      }
    };
  };

  // 获取坐标系配置
  const getCoordinateOptions = () => {
    // 饼图、漏斗图、仪表盘不需要坐标轴
    if (chartStyle.chartType === 'pie' || chartStyle.chartType === 'funnel' || chartStyle.chartType === 'gauge') {
      return {};
    }

    return {
      grid: {
        show: chartStyle.gridShow,
        left: chartStyle.showLeftAxis ? (chartStyle.axisPaddingShow ? '10%' : '10%') : '0%',
        right: chartStyle.showRightAxis ? '5%' : '0%',
        top: chartStyle.showTopAxis ? '18%' : '12%', // 为标题留出更多空间
        bottom: chartStyle.showBottomAxis ? (chartStyle.axisPaddingShow ? '15%' : '15%') : '0%',
        containLabel: true,
        borderColor: chartStyle.gridColor,
        borderWidth: 1,
        borderType: chartStyle.gridType
      },
      xAxis: [
        {
          ...xAxisConfigBottom,
          // 底部x轴
          show: chartStyle.showBottomAxis,
          type: axisTypes.xAxisType, // 根据数据自动设置轴类型
          position: 'bottom',
          // 分类轴不需要设置数值范围和间隔
          ...(axisTypes.xAxisType === 'value' ? {
            min: chartStyle.xScaleAdjustment === 'nice'
              ? calculateNiceRange(chartStyle.xScaleStart, chartStyle.xScaleEnd).start
              : chartStyle.xScaleStart,
            max: chartStyle.xScaleAdjustment === 'nice'
              ? calculateNiceRange(chartStyle.xScaleStart, chartStyle.xScaleEnd).end
              : chartStyle.xScaleEnd,
            interval: calculateInterval(
              chartStyle.xScaleStart,
              chartStyle.xScaleEnd,
              chartStyle.xMajorScaleValue,
              chartStyle.xMajorScaleType
            ),
          } : {}),
          inverse: chartStyle.xIsFlipped,
          scale: true,
          axisLine: {
            show: chartStyle.bottomAxisLineShow,
            onZero: false,
            lineStyle: {
              color: chartStyle.bottomAxisLineColor,
              width: chartStyle.bottomAxisLineWidth
            },
            symbol: chartStyle.bottomAxisLineArrow ? ['none', 'arrow'] : undefined,
            symbolSize: chartStyle.bottomAxisLineArrow ? [8, 16] : undefined
          },
          axisTick: {
            show: chartStyle.bottomMajorTickShow,
            length: chartStyle.bottomMajorTickLength,
            lineStyle: {
              color: chartStyle.bottomMajorTickColor,
              width: chartStyle.bottomMajorTickWidth
            },
            splitNumber: chartStyle.xMinorScaleCount,
            inside: chartStyle.bottomMajorTickType === 'inside'
          },
          minorTick: {
            show: chartStyle.bottomMinorTickShow,
            length: chartStyle.bottomMinorTickLength,
            lineStyle: {
              color: chartStyle.bottomMinorTickColor,
              width: chartStyle.bottomMinorTickWidth
            },
            inside: chartStyle.bottomMinorTickType === 'inside',
            splitNumber: 4
          },
          axisLabel: {
            show: chartStyle.bottomAxisLabelShow ?? true,
            color: chartStyle.bottomAxisLabelColor || "#666666",
            fontSize: chartStyle.bottomAxisLabelFontSize || 12,
            fontFamily: chartStyle.bottomAxisLabelFontFamily || "Microsoft YaHei",
            rotate: chartStyle.bottomAxisLabelRotate || 0,
            margin: chartStyle.bottomAxisLabelDistance || 8
          },
          // 轴标题配置
          name: chartStyle.bottomAxisTitleShow ? (chartStyle.bottomAxisTitleText || '') : '',
          nameTextStyle: {
            color: chartStyle.bottomAxisTitleColor || '#000',
            fontSize: chartStyle.bottomAxisTitleFontSize || 16,
            fontFamily: chartStyle.bottomAxisTitleFontFamily || 'SimSun',
          },
          nameLocation: chartStyle.bottomAxisTitlePosition || 'middle',
          nameRotate: chartStyle.bottomAxisTitleRotate || 0,
          ...xGrid,
        },
        {
          ...xAxisConfigTop,
          // 顶部x轴
          show: chartStyle.showTopAxis,
          type: axisTypes.xAxisType, // 根据数据自动设置轴类型
          position: 'top',
          // 分类轴不需要设置数值范围和间隔
          ...(axisTypes.xAxisType === 'value' ? {
            min: chartStyle.xScaleAdjustment === 'nice'
              ? calculateNiceRange(chartStyle.xScaleStart, chartStyle.xScaleEnd).start
              : chartStyle.xScaleStart,
            max: chartStyle.xScaleAdjustment === 'nice'
              ? calculateNiceRange(chartStyle.xScaleStart, chartStyle.xScaleEnd).end
              : chartStyle.xScaleEnd,
            interval: calculateInterval(
              chartStyle.xScaleStart,
              chartStyle.xScaleEnd,
              chartStyle.xMajorScaleValue,
              chartStyle.xMajorScaleType
            ),
          } : {}),
          inverse: chartStyle.xIsFlipped,
          scale: true,
          axisLine: {
            show: chartStyle.topAxisLineShow,
            onZero: false,
            lineStyle: {
              color: chartStyle.topAxisLineColor,
              width: chartStyle.topAxisLineWidth
            },
            symbol: chartStyle.topAxisLineArrow ? ['none', 'arrow'] : undefined,
            symbolSize: chartStyle.topAxisLineArrow ? [8, 16] : undefined
          },
          axisTick: {
            show: chartStyle.topMajorTickShow,
            length: chartStyle.topMajorTickLength,
            lineStyle: {
              color: chartStyle.topMajorTickColor,
              width: chartStyle.topMajorTickWidth
            },
            splitNumber: chartStyle.xMinorScaleCount,
            inside: chartStyle.topMajorTickType === 'inside'
          },
          minorTick: {
            show: chartStyle.topMinorTickShow,
            length: chartStyle.topMinorTickLength,
            lineStyle: {
              color: chartStyle.topMinorTickColor,
              width: chartStyle.topMinorTickWidth
            },
            inside: chartStyle.topMinorTickType === 'inside',
            splitNumber: 4
          },
          axisLabel: {
            show: chartStyle.topAxisLabelShow ?? true,
            color: chartStyle.topAxisLabelColor || "#666666",
            fontSize: chartStyle.topAxisLabelFontSize || 12,
            fontFamily: chartStyle.topAxisLabelFontFamily || "Microsoft YaHei",
            rotate: chartStyle.topAxisLabelRotate || 0,
            margin: chartStyle.topAxisLabelDistance || 8
          },
          // 轴标题配置
          name: chartStyle.topAxisTitleShow ? (chartStyle.topAxisTitleText || '') : '',
          nameTextStyle: {
            color: chartStyle.topAxisTitleColor || '#000',
            fontSize: chartStyle.topAxisTitleFontSize || 16,
            fontFamily: chartStyle.topAxisTitleFontFamily || 'SimSun',
          },
          nameLocation: chartStyle.topAxisTitlePosition || 'middle',
          nameRotate: chartStyle.topAxisTitleRotate || 0,
          ...xGrid,
        }
      ],
      yAxis: [
        {
          ...yAxisConfigLeft,
          // 左侧y轴
          show: chartStyle.showLeftAxis,
          ...getEchartsAxisTypeAndParams(chartStyle.yScaleType),
          position: 'left',
          min: chartStyle.yScaleAdjustment === 'nice'
            ? calculateNiceRange(chartStyle.yScaleStart, chartStyle.yScaleEnd).start
            : chartStyle.yScaleStart,
          max: chartStyle.yScaleAdjustment === 'nice'
            ? calculateNiceRange(chartStyle.yScaleStart, chartStyle.yScaleEnd).end
            : chartStyle.yScaleEnd,
          interval: calculateInterval(
            chartStyle.yScaleStart,
            chartStyle.yScaleEnd,
            chartStyle.yMajorScaleValue,
            chartStyle.yMajorScaleType
          ),
          inverse: chartStyle.yIsFlipped,
          scale: true,
          axisLine: {
            show: chartStyle.leftAxisLineShow,
            onZero: false,
            lineStyle: {
              color: chartStyle.leftAxisLineColor,
              width: chartStyle.leftAxisLineWidth
            },
            symbol: chartStyle.leftAxisLineArrow ? ['none', 'arrow'] : undefined,
            symbolSize: chartStyle.leftAxisLineArrow ? [8, 16] : undefined
          },
          axisTick: {
            show: chartStyle.leftMajorTickShow,
            length: chartStyle.leftMajorTickLength,
            lineStyle: {
              color: chartStyle.leftMajorTickColor,
              width: chartStyle.leftMajorTickWidth
            },
            splitNumber: chartStyle.yMinorScaleCount,
            inside: chartStyle.leftMajorTickType === 'inside'
          },
          minorTick: {
            show: chartStyle.leftMinorTickShow,
            length: chartStyle.leftMinorTickLength,
            lineStyle: {
              color: chartStyle.leftMinorTickColor,
              width: chartStyle.leftMinorTickWidth
            },
            inside: chartStyle.leftMinorTickType === 'inside',
            splitNumber: 4
          },
          axisLabel: {
            show: chartStyle.leftAxisLabelShow ?? true,
            color: chartStyle.leftAxisLabelColor || "#666666",
            fontSize: chartStyle.leftAxisLabelFontSize || 12,
            fontFamily: chartStyle.leftAxisLabelFontFamily || "Microsoft YaHei",
            rotate: chartStyle.leftAxisLabelRotate || 0,
            margin: chartStyle.leftAxisLabelDistance || 8
          },
          // 轴标题配置
          name: chartStyle.leftAxisTitleShow ? (chartStyle.leftAxisTitleText || '') : '',
          nameTextStyle: {
            color: chartStyle.leftAxisTitleColor || '#000',
            fontSize: chartStyle.leftAxisTitleFontSize || 16,
            fontFamily: chartStyle.leftAxisTitleFontFamily || 'SimSun',
          },
          nameLocation: chartStyle.leftAxisTitlePosition || 'middle',
          nameRotate: chartStyle.leftAxisTitleRotate || 0,
          ...yGrid,
        },
        {
          ...yAxisConfigRight,
          // 右侧y轴
          show: chartStyle.showRightAxis,
          ...getEchartsAxisTypeAndParams(chartStyle.yScaleType),
          position: 'right',
          min: chartStyle.yScaleAdjustment === 'nice'
            ? calculateNiceRange(chartStyle.yScaleStart, chartStyle.yScaleEnd).start
            : chartStyle.yScaleStart,
          max: chartStyle.yScaleAdjustment === 'nice'
            ? calculateNiceRange(chartStyle.yScaleStart, chartStyle.yScaleEnd).end
            : chartStyle.yScaleEnd,
          interval: calculateInterval(
            chartStyle.yScaleStart,
            chartStyle.yScaleEnd,
            chartStyle.yMajorScaleValue,
            chartStyle.yMajorScaleType
          ),
          inverse: chartStyle.yIsFlipped,
          scale: true,
          axisLine: {
            show: chartStyle.rightAxisLineShow,
            onZero: false,
            lineStyle: {
              color: chartStyle.rightAxisLineColor,
              width: chartStyle.rightAxisLineWidth
            },
            symbol: chartStyle.rightAxisLineArrow ? ['none', 'arrow'] : undefined,
            symbolSize: chartStyle.rightAxisLineArrow ? [8, 16] : undefined
          },
          axisTick: {
            show: chartStyle.rightMajorTickShow,
            length: chartStyle.rightMajorTickLength,
            lineStyle: {
              color: chartStyle.rightMajorTickColor,
              width: chartStyle.rightMajorTickWidth
            },
            splitNumber: chartStyle.yMinorScaleCount,
            inside: chartStyle.rightMajorTickType === 'inside'
          },
          minorTick: {
            show: chartStyle.rightMinorTickShow,
            length: chartStyle.rightMinorTickLength,
            lineStyle: {
              color: chartStyle.rightMinorTickColor,
              width: chartStyle.rightMinorTickWidth
            },
            inside: chartStyle.rightMinorTickType === 'inside',
            splitNumber: 4
          },
          axisLabel: {
            show: chartStyle.rightAxisLabelShow ?? true,
            color: chartStyle.rightAxisLabelColor || "#666666",
            fontSize: chartStyle.rightAxisLabelFontSize || 12,
            fontFamily: chartStyle.rightAxisLabelFontFamily || "Microsoft YaHei",
            rotate: chartStyle.rightAxisLabelRotate || 0,
            margin: chartStyle.rightAxisLabelDistance || 8
          },
          // 轴标题配置
          name: chartStyle.rightAxisTitleShow ? (chartStyle.rightAxisTitleText || '') : '',
          nameTextStyle: {
            color: chartStyle.rightAxisTitleColor || '#000',
            fontSize: chartStyle.rightAxisTitleFontSize || 16,
            fontFamily: chartStyle.rightAxisTitleFontFamily || 'SimSun',
          },
          nameLocation: chartStyle.rightAxisTitlePosition || 'middle',
          nameRotate: chartStyle.rightAxisTitleRotate || 0,
          ...yGrid,
        }
      ]
    };
  };

  // 获取系列配置
  const getSeriesConfig = () => {
    // 创建单个系列配置的函数
    const createSingleSeriesConfig = (seriesData, seriesInfo, colorIndex) => {
      const baseConfig = {
        name: seriesInfo.name || `数据系列${colorIndex + 1}`,
        type: chartStyle.chartType
      };

      // 获取当前系列使用的颜色
      const seriesColor = chartStyle.seriesColors[colorIndex % chartStyle.seriesColors.length];

      // 根据图表类型添加特定配置
      switch (chartStyle.chartType) {
        case 'line':
          return {
            ...baseConfig,
            lineStyle: {
              color: seriesColor
            },
            itemStyle: {
              color: seriesColor
            },
            data: seriesData
          };

        case 'bar':
          return {
            ...baseConfig,
            barWidth: '60%',
            itemStyle: {
              color: seriesColor,
              borderRadius: [4, 4, 0, 0]
            },
            data: seriesData
          };

        case 'scatter':
          return {
            ...baseConfig,
            symbolSize: 8,
            itemStyle: {
              color: seriesColor,
              borderColor: '#fff',
              borderWidth: 2
            },
            data: seriesData
          };

        case 'area':
          return {
            ...baseConfig,
            type: 'line',
            areaStyle: {
              color: seriesColor + '4D' // 添加30%透明度
            },
            lineStyle: {
              color: seriesColor,
              width: 2
            },
            data: seriesData
          };

        default:
          return {
            ...baseConfig,
            lineStyle: {
              color: seriesColor
            },
            itemStyle: {
              color: seriesColor
            },
            data: seriesData
          };
      }
    };

    // 处理多系列数据
    if (data.multiSeries && data.allSeries) {
      return data.allSeries.map((series, index) =>
        createSingleSeriesConfig(series.line, series.seriesInfo, index)
      );
    }

    // 处理单系列数据（向后兼容）
    if (data.line) {
      // 对于饼图、漏斗图、仪表盘等单系列图表，使用原有逻辑
      if (chartStyle.chartType === 'pie') {
        return {
          name: 'data',
          type: chartStyle.chartType,
          radius: ['40%', '70%'],
          center: ['50%', '50%'],
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: true,
            formatter: '{b}: {c} ({d}%)'
          },
          // 饼图使用多个颜色
          data: data.line.map((item, index) => ({
            value: Math.abs(item.value[1]), // 饼图使用绝对值
            name: `数据${index + 1}`,
            itemStyle: {
              color: chartStyle.seriesColors[index % chartStyle.seriesColors.length]
            }
          }))
        };
      } else if (chartStyle.chartType === 'funnel') {
        return {
          name: 'data',
          type: chartStyle.chartType,
          left: '10%',
          top: '10%',
          width: '80%',
          height: '80%',
          sort: 'descending',
          gap: 2,
          label: {
            show: true,
            position: 'inside'
          },
          labelLine: {
            show: false
          },
          itemStyle: {
            borderColor: '#fff',
            borderWidth: 1
          },
          emphasis: {
            label: {
              fontSize: 20
            }
          },
          // 漏斗图使用多个颜色
          data: data.line.map((item, index) => ({
            value: Math.abs(item.value[1]), // 漏斗图使用绝对值
            name: `阶段${index + 1}`,
            itemStyle: {
              color: chartStyle.seriesColors[index % chartStyle.seriesColors.length]
            }
          }))
        };
      } else if (chartStyle.chartType === 'gauge') {
        return {
          name: 'data',
          type: chartStyle.chartType,
          center: ['50%', '60%'],
          startAngle: 200,
          endAngle: -40,
          min: Math.min(...data.line.map(item => item.value[1])),
          max: Math.max(...data.line.map(item => item.value[1])),
          splitNumber: 5,
          itemStyle: {
            color: chartStyle.seriesColors[0]
          },
          progress: {
            show: true,
            width: 30
          },
          pointer: {
            show: true
          },
          axisLine: {
            lineStyle: {
              width: 30
            }
          },
          axisTick: {
            distance: -45,
            splitNumber: 5,
            lineStyle: {
              width: 2,
              color: '#999'
            }
          },
          splitLine: {
            distance: -52,
            length: 14,
            lineStyle: {
              width: 3,
              color: '#999'
            }
          },
          axisLabel: {
            distance: -20,
            color: '#999',
            fontSize: 20
          },
          anchor: {
            show: false
          },
          title: {
            show: false
          },
          detail: {
            valueAnimation: true,
            width: '60%',
            lineHeight: 40,
            borderRadius: 8,
            offsetCenter: [0, '-15%'],
            fontSize: 60,
            fontWeight: 'bolder',
            formatter: '{value}',
            color: 'inherit'
          },
          data: [
            {
              value: data.line.length > 0 ? data.line[data.line.length - 1].value[1] : 0,
              name: '当前值'
            }
          ]
        };
      } else {
        // 对于其他图表类型，使用第一个系列的数据
        return createSingleSeriesConfig(data.line, data.seriesInfo || { name: '数据系列' }, 0);
      }
    }

    // 返回空数组作为默认值
    return [];
  };

  // 合并所有配置
  const seriesConfig = getSeriesConfig();
  const options = {
    ...getBaseOptions(),
    ...getCoordinateOptions(),
    series: [
      // 处理多系列或单系列数据
      ...(Array.isArray(seriesConfig) ? seriesConfig : [seriesConfig]),
      // 添加水平参照线
      ...(chartStyle.hReferenceLineShow ? [{
        name: 'hReferenceLine',
        type: 'line',
        markLine: {
          symbol: 'none',
          lineStyle: {
            color: chartStyle.hReferenceLineColor,
            type: chartStyle.hReferenceLineType,
            width: chartStyle.hReferenceLineWidth
          },
          data: [
            {
              yAxis: chartStyle.hReferenceLineValue,
              label: {
                show: true,
                position: 'end',
                formatter: `Y: {c}`
              }
            }
          ]
        }
      }] : []),

      // 添加垂直参照线
      ...(chartStyle.vReferenceLineShow ? [{
        name: 'vReferenceLine',
        type: 'line',
        markLine: {
          symbol: 'none',
          lineStyle: {
            color: chartStyle.vReferenceLineColor,
            type: chartStyle.vReferenceLineType,
            width: chartStyle.vReferenceLineWidth
          },
          data: [
            {
              xAxis: chartStyle.vReferenceLineValue,
              label: {
                show: true,
                position: 'end',
                formatter: `X: {c}`
              }
            }
          ]
        }
      }] : [])
    ],
    // 添加轴须图形元素（仅非饼图）
    graphic: (chartStyle.axisPaddingShow && chartStyle.chartType !== 'pie') ? calculateRugMarks() : [],
  };

  const handleStyleChange = (newStyle) => {
    setChartStyle(newStyle);
  };

  // 处理文件上传成功
  const handleDataLoaded = (newData, originalData) => {
    try {
      setData(newData);
      setError(null);

      // 生成状态信息
      let statusMessage = '';
      if (newData.multiSeries && newData.allSeries) {
        statusMessage = `多系列数据加载成功: ${newData.allSeries.length}个系列`;
      } else {
        statusMessage = `数据加载成功: ${originalData.series[0]?.name || '未命名数据'}`;
      }
      setUploadStatus(statusMessage);

      // 根据新数据更新刻度范围配置
      const newDataRanges = calculateDataRanges(newData);

      setChartStyle(prevStyle => ({
        ...prevStyle,
        // 更新x轴范围（仅当x轴为数值类型时）
        ...(newDataRanges.xType === 'value' && newDataRanges.xMin !== null ? {
          xScaleStart: newDataRanges.xMin,
          xScaleEnd: newDataRanges.xMax,
        } : {}),
        // 更新y轴范围
        yScaleStart: newDataRanges.yMin,
        yScaleEnd: newDataRanges.yMax,
        // 计算合适的主刻度间隔
        ...(newDataRanges.xType === 'value' && newDataRanges.xMin !== null ? {
          xMajorScaleValue: Math.max(1, Math.ceil((newDataRanges.xMax - newDataRanges.xMin) / 8))
        } : {}),
        yMajorScaleValue: newDataRanges.yMajorScaleValue || Math.max(0.5, Math.ceil((newDataRanges.yMax - newDataRanges.yMin) / 6 * 2) / 2),
        // 只有当用户没有自定义标题时才使用数据中的标题
        ...((!prevStyle.titleText || prevStyle.titleText.trim() === '') && newData.title ? {
          titleText: newData.title
        } : {})
      }));

      console.log('新数据已加载:', newData);
      console.log('数据范围:', newDataRanges);
    } catch (error) {
      console.error('数据设置失败:', error);
      setError('数据设置失败');
    }
  };

  // 处理文件上传错误
  const handleUploadError = (errorMessage, validationResult) => {
    // 不设置error状态，避免阻止组件渲染
    // setError(errorMessage);
    setUploadStatus('数据加载失败');
    console.error('上传错误:', errorMessage, validationResult);
    // FileUploader内部会处理ErrorModal的显示
  };

  // 重置为模拟数据
  const resetToMockData = () => {
    const mockData = generateMockData();
    setData(mockData);
    setError(null);
    setUploadStatus('已重置为模拟数据');

    // 根据模拟数据更新刻度范围配置
    const mockDataRanges = calculateDataRanges(mockData);
    setChartStyle(prevStyle => ({
      ...prevStyle,
      // 更新x轴范围
      ...(mockDataRanges.xType === 'value' && mockDataRanges.xMin !== null ? {
        xScaleStart: mockDataRanges.xMin,
        xScaleEnd: mockDataRanges.xMax,
        xMajorScaleValue: Math.max(1, Math.ceil((mockDataRanges.xMax - mockDataRanges.xMin) / 8))
      } : {}),
      // 更新y轴范围
      yScaleStart: mockDataRanges.yMin,
      yScaleEnd: mockDataRanges.yMax,
      yMajorScaleValue: mockDataRanges.yMajorScaleValue || Math.max(0.5, Math.ceil((mockDataRanges.yMax - mockDataRanges.yMin) / 6 * 2) / 2)
    }));
  };

  // 确保在组件挂载时初始化所有必要的状态
  useEffect(() => {
    try {
      console.log('图表初始化，当前数据范围:', dataRanges);
      console.log('当前轴类型:', axisTypes);
    } catch (err) {
      console.error("Error initializing chart:", err);
      setError("初始化图表时出错");
    }
  }, [data]);

  // 如果出现错误，显示错误信息
  if (error) {
    return <div className="chart-error">{error}</div>;
  }

  // 饼图、漏斗图、仪表盘不需要轴，所以不进行轴的检查
  if (chartStyle.chartType !== 'pie' && chartStyle.chartType !== 'funnel' && chartStyle.chartType !== 'gauge' &&
    !chartStyle.showTopAxis && !chartStyle.showBottomAxis && !chartStyle.showLeftAxis && !chartStyle.showRightAxis) {
    return null;
  }

  // 获取图表实例的回调函数
  const handleChartReady = (instance) => {
    console.log("Chart instance ready:", instance);
    chartInstanceRef.current = instance;

    // 设置图表实例的事件处理
    if (instance) {
      // 添加图表渲染完成事件监听
      instance.on('rendered', () => {
        console.log('Chart rendered successfully');
      });

      // 添加错误事件监听
      instance.on('error', (error) => {
        console.error('Chart error:', error);
        setError(`图表渲染错误: ${error.message || '未知错误'}`);
      });
    }
  };





  return (
    <div style={{ position: 'relative' }}>
      {error && (
        <div style={{
          position: 'absolute',
          top: '50%',
          left: '50%',
          transform: 'translate(-50%, -50%)',
          backgroundColor: 'rgba(255, 0, 0, 0.1)',
          padding: '10px 20px',
          borderRadius: '4px',
          border: '1px solid #f44336',
          color: '#f44336',
          zIndex: 10
        }}>
          {error}
          <button
            onClick={() => setError(null)}
            style={{
              marginLeft: '10px',
              padding: '2px 6px',
              backgroundColor: 'transparent',
              border: '1px solid #f44336',
              borderRadius: '4px',
              color: '#f44336',
              cursor: 'pointer'
            }}
          >
            关闭
          </button>
        </div>
      )}
      <OriginChart
        options={options}
        onChartReady={handleChartReady}
      />
      {modalVisible && (
        <ChartStyleModal
          visible={modalVisible}
          onClose={() => setModalVisible(false)}
          onStyleChange={handleStyleChange}
          initialStyle={chartStyle}
          dataRanges={dataRanges}
        />
      )}

      {uploaderVisible && (
        <div style={{
          position: 'fixed',
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          backgroundColor: 'rgba(0, 0, 0, 0.5)',
          zIndex: 1000,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center'
        }}>
          <div style={{
            backgroundColor: '#fff',
            borderRadius: '8px',
            padding: '20px',
            maxWidth: '600px',
            width: '90%',
            maxHeight: '80vh',
            overflow: 'auto'
          }}>
            <div style={{
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center',
              marginBottom: '20px'
            }}>
              <h3 style={{ margin: 0 }}>上传JSON数据文件</h3>
              <button
                onClick={() => setUploaderVisible(false)}
                style={{
                  background: 'none',
                  border: 'none',
                  fontSize: '18px',
                  cursor: 'pointer',
                  padding: '4px'
                }}
              >
                ✕
              </button>
            </div>
            <FileUploader
              onDataLoaded={handleDataLoaded}
              onError={handleUploadError}
            />
            {uploadStatus && (
              <div style={{
                marginTop: '16px',
                padding: '8px 12px',
                backgroundColor: '#f0f8ff',
                borderRadius: '4px',
                fontSize: '14px',
                color: '#1890ff'
              }}>
                {uploadStatus}
              </div>
            )}
          </div>
        </div>
      )}

      <div style={{ position: 'absolute', top: -25, right: 0, display: 'flex', gap: '10px', flexWrap: 'wrap' }}>
        <button
          onClick={() => setUploaderVisible(true)}
          style={{
            padding: '6px 12px',
            backgroundColor: '#fff',
            border: '1px solid #000',
            borderRadius: '4px',
            cursor: 'pointer',
            fontSize: '12px'
          }}
        >
          上传数据
        </button>
        <button
          onClick={resetToMockData}
          style={{
            padding: '6px 12px',
            backgroundColor: '#fff',
            border: '1px solid #666',
            borderRadius: '4px',
            cursor: 'pointer',
            fontSize: '12px',
            color: '#666'
          }}
        >
          重置数据
        </button>
        <button
          onClick={() => setModalVisible(true)}
          style={{
            padding: '6px 12px',
            backgroundColor: '#fff',
            border: '1px solid #000',
            borderRadius: '4px',
            cursor: 'pointer',
            fontSize: '12px'
          }}
        >
          样式设置
        </button>
      </div>
    </div>
  );
};

export default ScatterLineChart; 